package com.xaicode.algorithm.etc;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.stream.IntStream;

/**
 * @author Locker cjxia@isoftstone.com
 * @version 1.0
 */
@Slf4j
public class MathTemplate {

    public static void main(String[] args) {
        double[] doubles = {1, 2, 3, 4, 5};
        double[] average = simpleMovingAverage(doubles, 2);
        System.out.println(Arrays.toString(average));


    }

    /**
     * 简单滑动平均数
     *
     * @param values 原始数据
     * @param n      滑动窗格
     * @return
     */
    public static double[] simpleMovingAverage(double[] values, int n) {
        double[] doubles = Arrays.copyOf(values, values.length);
        Arrays.parallelPrefix(doubles, Double::sum);
        System.out.println(Arrays.toString(doubles));
        int start = n - 1;
        return IntStream.range(start, doubles.length)
                .mapToDouble(i -> {
                    double prefix = i == start ? 0 : doubles[i - n];

                    log.info("start={}, i={}, prefix={}", start, i, prefix);
                    log.info("  doubles[{}]={}, double - prefix = {}", i, doubles[i], doubles[i] - prefix);

                    return (doubles[i] - prefix) / n;
                })
                .toArray();
    }

}
